/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;

import bean.Promotion;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import bean.Vehicule;
import dao.exceptions.IllegalOrphanException;
import dao.exceptions.NonexistentEntityException;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

/**
 *
 * @author mezouari
 */
public class PromotionJpaController implements Serializable {

    public PromotionJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Promotion promotion) {
        if (promotion.getVehiculeList() == null) {
            promotion.setVehiculeList(new ArrayList<Vehicule>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Vehicule> attachedVehiculeList = new ArrayList<Vehicule>();
            for (Vehicule vehiculeListVehiculeToAttach : promotion.getVehiculeList()) {
                vehiculeListVehiculeToAttach = em.getReference(vehiculeListVehiculeToAttach.getClass(), vehiculeListVehiculeToAttach.getId());
                attachedVehiculeList.add(vehiculeListVehiculeToAttach);
            }
            promotion.setVehiculeList(attachedVehiculeList);
            em.persist(promotion);
            for (Vehicule vehiculeListVehicule : promotion.getVehiculeList()) {
                Promotion oldIdPromotionOfVehiculeListVehicule = vehiculeListVehicule.getIdPromotion();
                vehiculeListVehicule.setIdPromotion(promotion);
                vehiculeListVehicule = em.merge(vehiculeListVehicule);
                if (oldIdPromotionOfVehiculeListVehicule != null) {
                    oldIdPromotionOfVehiculeListVehicule.getVehiculeList().remove(vehiculeListVehicule);
                    oldIdPromotionOfVehiculeListVehicule = em.merge(oldIdPromotionOfVehiculeListVehicule);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Promotion promotion) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Promotion persistentPromotion = em.find(Promotion.class, promotion.getId());
            List<Vehicule> vehiculeListOld = persistentPromotion.getVehiculeList();
            List<Vehicule> vehiculeListNew = promotion.getVehiculeList();
            List<String> illegalOrphanMessages = null;
            for (Vehicule vehiculeListOldVehicule : vehiculeListOld) {
                if (!vehiculeListNew.contains(vehiculeListOldVehicule)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Vehicule " + vehiculeListOldVehicule + " since its idPromotion field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<Vehicule> attachedVehiculeListNew = new ArrayList<Vehicule>();
            for (Vehicule vehiculeListNewVehiculeToAttach : vehiculeListNew) {
                vehiculeListNewVehiculeToAttach = em.getReference(vehiculeListNewVehiculeToAttach.getClass(), vehiculeListNewVehiculeToAttach.getId());
                attachedVehiculeListNew.add(vehiculeListNewVehiculeToAttach);
            }
            vehiculeListNew = attachedVehiculeListNew;
            promotion.setVehiculeList(vehiculeListNew);
            promotion = em.merge(promotion);
            for (Vehicule vehiculeListNewVehicule : vehiculeListNew) {
                if (!vehiculeListOld.contains(vehiculeListNewVehicule)) {
                    Promotion oldIdPromotionOfVehiculeListNewVehicule = vehiculeListNewVehicule.getIdPromotion();
                    vehiculeListNewVehicule.setIdPromotion(promotion);
                    vehiculeListNewVehicule = em.merge(vehiculeListNewVehicule);
                    if (oldIdPromotionOfVehiculeListNewVehicule != null && !oldIdPromotionOfVehiculeListNewVehicule.equals(promotion)) {
                        oldIdPromotionOfVehiculeListNewVehicule.getVehiculeList().remove(vehiculeListNewVehicule);
                        oldIdPromotionOfVehiculeListNewVehicule = em.merge(oldIdPromotionOfVehiculeListNewVehicule);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = promotion.getId();
                if (findPromotion(id) == null) {
                    throw new NonexistentEntityException("The promotion with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Promotion promotion;
            try {
                promotion = em.getReference(Promotion.class, id);
                promotion.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The promotion with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Vehicule> vehiculeListOrphanCheck = promotion.getVehiculeList();
            for (Vehicule vehiculeListOrphanCheckVehicule : vehiculeListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Promotion (" + promotion + ") cannot be destroyed since the Vehicule " + vehiculeListOrphanCheckVehicule + " in its vehiculeList field has a non-nullable idPromotion field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(promotion);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Promotion> findPromotionEntities() {
        return findPromotionEntities(true, -1, -1);
    }

    public List<Promotion> findPromotionEntities(int maxResults, int firstResult) {
        return findPromotionEntities(false, maxResults, firstResult);
    }

    private List<Promotion> findPromotionEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Promotion.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Promotion findPromotion(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Promotion.class, id);
        } finally {
            em.close();
        }
    }

    public int getPromotionCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Promotion> rt = cq.from(Promotion.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
